package com.hzncc.flowable_diboot.controller.refundmanage;

import com.diboot.core.util.V;
import com.diboot.core.util.S;
import com.diboot.core.util.ContextHolder;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.LabelValue;
import com.diboot.core.vo.Pagination;
import com.diboot.core.controller.BaseCrudRestController;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.hzncc.flowable_diboot.entity.refundmanage.RefundContract;
import com.hzncc.flowable_diboot.payment.entity.PaymentContract;
import com.hzncc.flowable_diboot.payment.entity.PaymentRegister;
import com.hzncc.flowable_diboot.service.refundmanage.RefundContractService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import com.hzncc.flowable_diboot.entity.refundmanage.RefundRegister;
import com.hzncc.flowable_diboot.service.refundmanage.RefundRegisterService;
import com.hzncc.flowable_diboot.vo.refundmanage.RefundRegisterDetailVO;
import com.hzncc.flowable_diboot.vo.refundmanage.RefundRegisterListVO;
import com.hzncc.flowable_diboot.dto.refundmanage.RefundRegisterDTO;

import java.io.Serializable;
import java.util.List;

/**
* 退款登记 相关rest接口
* @author MyName
* @version 1.0
* @date 2024-11-08
* Copyright © MyCorp
*/
@Slf4j
@RequestMapping("/refund-manage/refund-register")
@BindPermission(name = "退款登记")
@RestController
public class RefundRegisterController extends BaseCrudRestController<RefundRegister> {

    @Autowired
    private RefundRegisterService refundRegisterService;

    @Autowired
    private RefundContractService refundContractService;

    /**
    * 查询资源对象的列表VO记录
    * <p>
    * url请求参数示例: ?fieldA=abc&pageSize=20&pageIndex=1&orderBy=id
    * </p>
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping()
    public JsonResult<List<RefundRegisterListVO>> getListVOMapping(RefundRegisterDTO queryDto, Pagination pagination) throws Exception {
        return JsonResult.OK(refundRegisterService.getRefundRegisterList(queryDto,pagination)).bindPagination(pagination);
    }

    /**
    * 根据id查询资源对象的详情VO
    * @param id ID
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult<RefundRegisterDetailVO> getDetailVOMapping(@PathVariable("id")String id) throws Exception {
        RefundRegisterDetailVO detailVO = refundRegisterService.getViewObject(id, RefundRegisterDetailVO.class);
        return JsonResult.OK(detailVO);
    }

/**
    * 根据指定字段和值查询资源对象的详情VO
    * @param fieldName 字段名
    * @param fieldValue 字段值
    * @return
    * @throws Exception
    */
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{fieldName}/{fieldValue}")
    public JsonResult<RefundRegisterDetailVO> getDetailVOMapping(@PathVariable("fieldName") String fieldName, @PathVariable("fieldValue") String fieldValue) throws Exception {
        RefundRegisterDetailVO detailVO = refundRegisterService.getViewObject(fieldName, fieldValue, RefundRegisterDetailVO.class);
        return JsonResult.OK(detailVO);
    }


    /**
    * 创建资源对象数据
    * @param refundRegister
    * @return JsonResult
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping()
    public JsonResult<Serializable> createModelMapping(@RequestBody RefundRegisterListVO refundRegister) throws Exception {
        refundRegisterService.createRefundRegister(refundRegister);
//        refundRegisterService.createEntity(refundRegister);
        return JsonResult.OK(refundRegister.getId());
    }

    /**
    * 根据id更新资源对象
    * @param refundRegister
    * @return JsonResult
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult<?> updateModelMapping(@PathVariable("id")String id, @RequestBody RefundRegisterListVO refundRegister) throws Exception {
        refundRegisterService.updateEntity(refundRegister);
        return JsonResult.OK();
    }

    /**
    * 根据id删除资源对象
    * @param id
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteModelMapping(@PathVariable("id") String id) throws Exception {
        boolean success = refundRegisterService.deleteEntity(id);
        log.debug("删除数据 退款登记:{} {}", id, success? "成功":"失败");
        return JsonResult.OK();
    }

    /**
    * 根据ids集合删除资源对象
    * @param ids
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_BATCH_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch-delete")
    public JsonResult<?> deleteEntityMapping(@RequestBody List<String> ids) throws Exception {
        boolean success = refundRegisterService.deleteEntities(ids);
        log.debug("批量删除数据 退款登记:{} {}", ids, success? "成功":"失败");
        return JsonResult.OK();
    }

    /**
     * 检查退款状态
     *
     * @param id
     * @return
     */
    @GetMapping("/check-status/{id}")
    public JsonResult<?> checkRefundStatus(@PathVariable String id) {
        RefundRegister entity = refundRegisterService.getEntity(id);
        if (S.equals(entity.getCerted(),"1")){
            return JsonResult.FAIL_VALIDATION("已生成回款凭证，无法生成回款凭证");
        }
        List<RefundContract> entityList = refundContractService.getEntityList(refundContractService.lambdaQuery().eq(RefundContract::getRefundRegisterId, entity.getId()));
        if (entityList.stream().anyMatch(e -> !S.equals(e.getProcessState(), "2"))) {
            return JsonResult.FAIL_VALIDATION("回款有审批未完成或审批未通过的合同收款数据");
        }
        return JsonResult.OK();
    }

    /**
     * 批量检查收款状态
     * @param ids
     * @return
     */
    @GetMapping("/batch-check-status")
    public JsonResult<?> batchCheckPaymentStatus(@RequestParam List<String> ids) {
        List<RefundRegister> refundRegisterList = refundRegisterService.getEntityListByIds(ids);
        if (CollectionUtils.isEmpty(refundRegisterList)){
            return JsonResult.FAIL_VALIDATION("退款登记不存在");
        }
        for (RefundRegister refundRegister : refundRegisterList){
            if (S.equals(refundRegister.getCerted(),"1")){
                return JsonResult.FAIL_VALIDATION("已生成回款凭证，无法生成回款凭证");
            }
            List<RefundContract> entityList = refundContractService.getEntityList(refundContractService.lambdaQuery().eq(RefundContract::getRefundRegisterId, refundRegister.getId()));
            if (entityList.stream().anyMatch(e -> !S.equals(e.getProcessState(), "2"))) {
                return JsonResult.FAIL_VALIDATION("回款有审批未完成或审批未通过的合同收款数据");
            }
        }
        return JsonResult.OK();
    }

}